<template>
  <div class="app-container">
    <!-- 搜索条件 -->
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="漫画名称" v-model="keyword">
      </el-input>

     

      <!-- <el-select clearable class="filter-item" style="width: 130px" v-model="listQuery.type" placeholder="类型">
        <el-option v-for="item in  typeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key">
        </el-option>
      </el-select> -->

      <el-button class="filter-item" type="primary" v-waves icon="search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" type="primary" @click="handleCreate"  icon="edit">添加</el-button>

      <el-button class="filter-item" type="primary" @click="handleDelAll"  icon="edit">批量删除</el-button>
      <el-button class="filter-item" type="primary" icon="document" @click="handleDownload">导出</el-button>
     
    </div>

    
   
    <!-- 表格 -->
    <el-table ref="multipleTable" @selection-change="handleSelectionChange" :data="comics"  element-loading-text="拼命加载中" border fit highlight-current-row  >
         <el-table-column type="selection" width="40">
         </el-table-column>

          <el-table-column align="center" label='序号' width="65">
            <template slot-scope="scope">
              {{scope.$index}}
            </template>
          </el-table-column>

          <el-table-column align="center"  label="封面" width="100" >
                <template slot-scope="scope">
                  <el-image :src="scope.row.comic_cover" fit="cover" ></el-image>
                </template>
            </el-table-column>

          <el-table-column label="漫画名称" align="center" width="180">
            <template slot-scope="scope">
             <router-link :to="`/comicsManage/chaptersManage/comicChapList?comic_id=${scope.row.comic_id}`">{{scope.row.comic_title}}</router-link> 
            </template>
          </el-table-column>

          <el-table-column label="类别" align="center" width="90">
            <template slot-scope="scope">
              {{scope.row.comic_type}}
            </template>
          </el-table-column>

          <el-table-column label="作者"  align="center" width="100">
            <template slot-scope="scope">
              {{scope.row.comic_author}}
            </template>
          </el-table-column>

          <el-table-column align="center" prop="created_at" label="简介" width="200">
            <template slot-scope="scope">
              {{scope.row.comic_intro}}
            </template>
          </el-table-column>

          <el-table-column label="状态" align="center" width="70">
            <template slot-scope="scope">
              {{scope.row.comic_state}}
            </template>
          </el-table-column>

            <el-table-column align="center"  label="操作" >
                <template slot-scope="scope">
                  <el-button size="small" @click="handleShow(scope.row)">查看海报</el-button>
                  <el-button size="small" @click="handleSet(scope.row)">设置海报</el-button>
                  <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                         
                </template>
            </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.currPage"
        :page-sizes="[10,20,30, 50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
     <el-dialog
    title="查看海报"
    :visible.sync="dialogVisible"
    width="50%"
    @close="closeBanner">
      <el-form ref="bannerForm" :model="banner" label-width="80px">
        <el-form-item label="海报">
             <el-image :lazy='true' :z-index="2555" v-if="banner.banner_url" :src="banner.banner_url" fit="cover" style="width:250px" :preview-src-list="[banner.banner_url]"></el-image>
            <el-upload
              :disabled="!is_set"
              class="upload-demo"
              :action="`${$http.defaults.baseURL}/upload_banner`"
              :on-success="afterUpload" 
              >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
        </el-form-item>
        <el-form-item label="是否推荐" v-if="$store.getters.userInfo.grade === 'admin'">
          <el-checkbox v-model="banner.is_recommend" :disabled="!is_set">推荐</el-checkbox>
        </el-form-item>
        <el-form-item label="推荐时间" v-if="$store.getters.userInfo.grade === 'admin'">
          <!-- 设置value-format v-model值显示格式也是按这个 -->
            <el-date-picker
              v-model="banner.recommend_at"  
              :disabled="!is_set"
               value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              placeholder="选择日期时间">
            </el-date-picker>
        </el-form-item>
      </el-form>
    
      <span slot="footer" class="dialog-footer" v-if="is_set">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="commitBanner">确 定</el-button>
      </span>
  </el-dialog>
    <!-- 新增弹窗 -->
    <el-dialog title="表单新增" :visible.sync="dialogFormVisible">
          <el-form class="small-space" :model="temp" label-position="left" label-width="70px" style='width: 400px; margin-left:50px;'>
         
           

            <el-form-item label="字段1">
              <el-input v-model="temp.chnlId"></el-input>
            </el-form-item>

            <el-form-item label="字段2">
              <el-input v-model="temp.hisChnlId"></el-input>
            </el-form-item>

            <el-form-item label="字段3">
              <el-input v-model="temp.chnlName"></el-input>
            </el-form-item>

            <el-form-item label="字段4">
              <el-input v-model="temp.state"></el-input>
            </el-form-item>

           
          </el-form>

          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
           
            <el-button type="primary" @click="handleCreateSubmit">确 定</el-button>
          </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    return {

        list: null,//表格list [].push({})
        total: null,
        listQuery: {
            currPage: 1,
            pageSize: 10,
       
        },
        keyword:'',
        temp: {
          "chnlId": "",
          "hisChnlId": "",
          "chnlName": "",
          "state": "",
          "isavailable": "",
          "orderNum": 10
        },
        typeOptions:[
          { key: '001', display_name: '类型1' },
          { key: '002', display_name: '类型2' },
          { key: '003', display_name: '类型3' }
         
        ],
        dialogFormVisible: false,
        multipleSelection: [],
        comics:[],
        banner:{
          title:'作品名称',
          table_title :'comic_book',
          banner_url:'',
          is_recommend:'',
          recommend_at:'',
          work_id:'',
        },
        dialogVisible:false,
        copyBanner:{},
        is_set:false,//判断是否是设置海报还是查看海报

    }
  },
   mounted() {
    this.copyBanner = JSON.parse(JSON.stringify(this.banner))
    this.getList();
  },
  methods: {
     afterUpload(res){
      this.$set(this.banner, 'banner_url', res.url)
    }, 
     closeBanner(){
      this.dialogVisible = false
      this.banner = this.copyBanner
    },
    // 展示banner
    async handleShow(row){    
      console.log(row);
      this.is_set = false;
      this.banner.work_id = row.comic_id;
      let res = await this.$http.get('/get_banner', {params:this.banner})
      this.banner = res.data || this.banner
      this.dialogVisible = true;
    },
    // 展示banner，和设置banner
   async  handleSet(row){
     this.is_set = true;
      this.banner.work_id = row.comic_id;
      let res = await this.$http.get('/get_banner', {params:this.banner})
      this.banner = res.data || this.banner
      console.log(res.data);
      this.dialogVisible = true;
    },
    // 上传banner的确认键
   async commitBanner(){
     let res =  await this.$http.put('/update_banner', this.banner)
      this.$message({
        type:res.data.type,
        message:res.data.message
      })
      this.dialogVisible = false;
      this.banner = this.copyBanner;
      console.log(this.banner);
    },
    //获取列表数据
    async getList() {
          let res = await this.$http.get('/comics',{params:{user_id:this.$store.getters.userInfo.user_id,
                            pageSize:this.listQuery.pageSize, currPage:this.listQuery.currPage}})
          this.comics = res.data.comics
          this.listQuery.currPage = parseInt(res.data.currPage)
          this.listQuery.pageSize = parseInt(res.data.pageSize)
          this.total = res.data.total
          console.log(res.data);
    },
     //编辑
    handleEdit(index,row){
      this.$store.commit('SET_COMIC', row)
        console.log('编辑的row：',index,'-----',row);
        this.$router.push( '/comicsManage/comicUpdate' )
    },

    //单个删除
    handleDelete(index,row){
        let vm = this;
        console.log('单个删除选择的row：',index,'-----',row);
        
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
          vm.delFun(row);
          //前端删除。
          vm.comics.splice(index,1)

        }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });          
        });

    },
    //调取删除接口的删除方法
   async delFun(row){
      let comic_id = row.comic_id;
      let res = await this.$http.delete('/delete_comic',{params:{comic_id}})
      this.$message({
        type:res.data.type,
        message:res.data.message
      })
    },
    //批量删除
    handleDelAll(){
        let vm = this;
        console.log('批量删除选择的row：',vm.multipleSelection)
        
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
            confirmButtonText: '确定批量删除',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            //前端依次执行单个删除操作
           vm.comics = vm.comics.filter((item)=>{
              for(let selection of vm.multipleSelection){
                if(item.comic_id === selection.comic_id){
                  return false
                }
              }
              return true;
            })
          for (var index in vm.multipleSelection) {
              console.log('======',vm.multipleSelection[index])
              vm.delFun(vm.multipleSelection[index]);
          };

        }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });          
        });
    },
    //搜索
   async handleFilter() {
      let user_id = this.$store.getters.userInfo.user_id
      let res = await this.$http.get('/search_comic',{params:{user_id, keyword:this.keyword, pageSize:this.listQuery.pageSize, currPage:this.listQuery.currPage}})
      this.comics = res.data.comics;
      this.listQuery.currPage = parseInt(res.data.currPage)
      this.listQuery.pageSize = parseInt(res.data.pageSize)
      this.total = res.data.total
      console.log(res.data);
    },
    //操作分页
    handleSizeChange(val) {
      this.listQuery.pageSize = val;
      this.getList();
    },
    //操作分页
    handleCurrentChange(val) {
        console.log('--------',val)
      this.listQuery.currPage = val;
      this.getList();
    },
    //新增
    handleCreate() {
        //跳到新增页面
        this.$router.push('/comicsManage/comicAdd')
    },
    //新增提交
    handleCreateSubmit(){
        let vm = this;
        console.log('新增入参：',vm.temp)

        //这里作演示用，正式新增 请提交到接口
        vm.list.push(vm.temp)
        console.log('新增后',vm.list)
        
        this.dialogFormVisible = false;
    },
    handleSelectionChange(val) {
        this.multipleSelection = val;
    },



    handleDownload() {
      let vm = this;

      require.ensure([], () => {
        const { export_json_to_excel } = require('vendor/Export2Excel');
        const tHeader = ['漫画名', '作者', '类型', '介绍', '状态', '封面'];
        const filterVal = ['comic_title', 'comic_author', 'comic_type', 'comic_intro', 'comic_state', 'comic_cover' ];
        const list = vm.comics;
        const data = vm.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, '漫画表');
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    }
  }
};
</script>
<style>
a{
  color:#ed4259;
}
a:hover{
  color:#ed4259;
  font-weight: 700;
}
</style>